// vp_cai/pages/index/areas.js
var app = getApp();
var vp = require('../../resource/js/vp.js');
Page({
  data: {
    currentSwiperIndex: 0,
	is_vip:false,
	sessionFrom:'',
	quanyi:['专属家庭医生服务','24小时在线咨询','用药提醒定制服务','专家预约绿色通道'],
	currentTab: 'medical', // 当前选中的tab
	vipNum:0,
    activeUser: {
      
    },
    users: [
      
    ],
	imageOpacity: 1, // 控制大图淡入淡出效果
    medicalRecords: [
      { type: 'outpatient', name: '门诊病历' ,show:false},
		{ type: 'prescription', name: '门诊处方',show:false },
		{ type: 'discharge', name: '出院记录' ,show:false},
		{ type: 'physical', name: '体检报告',show:false },
		{ type: 'report', name: '报告单' ,show:false}
    ],
	MedicalInfo:[],
	// 健康史数据
	drinking:'',
	smoking:'',
	healthData: {
	  family: {
		description: []
	  },
	  personal: {
		
	  },
	  past: {
		
	  },
	},
	// 用药计划数据
	medicationPlans: [
	  
	],
	selectedContent:[],
	processedList: [],//重新组装的权益数据
  },
  // 切换用户
  // 切换用户 - 修改后版本
    switchUser: function(e) {
      const userId = parseInt(e.currentTarget.dataset.id);
      const user = this.data.users.find(item => item.id === userId);
      
      if (user && user.id !== this.data.activeUser.id) {
        // 先淡出当前图片
        this.setData({
          imageOpacity: 0
        });
        wx.setStorageSync('activeUser',user)
		this.setData({
		  currentTab: 'medical',
		  activeUser: user,
		});
        // 300ms后切换用户并淡入新图片
        setTimeout(() => {
          this.setData({
            imageOpacity: 1
          });
        }, 300);		
		this.getHealthNoteData()
		this.getMedicalInfo()
		this.getMedicalPlanOnGoing()
      }
    },

  // swiper切换回调
  swiperChange: function(e) {
    const current = e.detail.current;
    this.setData({
      currentSwiperIndex: current,
      activeUser: this.data.users[current]
    });
  },

  //删除当前用户
  deleteUser: function(){
	  let id = this.data.activeUser.id
	  var that = this
	    app.util.request({
	  	  url: 'Familydoctor/deleteUser',
	  	  data: {id:id},
	  	  success(res) {
	  		  that.getFamilyData()
	  	  }
	    })
  },
  // 添加用户
  addUser: function() {
	  const that = this
    wx.showModal({
      title: '添加家庭成员',
      content: '请输入家庭成员信息',
      success(res) {
        if (res.confirm) {
          wx.setStorageSync('can_edit_baseinfo',true)
		  wx.setStorageSync('activeUser',{})
          wx.navigateTo({
            url: '/vp_pz/pages/familydoctor/baseinfo?is_edit=true'
          });
        }
      }
    });
  },

  // 导航到各功能页面
  //基本信息
  navigateToHealthTest: function() {
	wx.setStorageSync('can_edit_baseinfo',false)
    wx.navigateTo({
      url: '/vp_pz/pages/familydoctor/baseinfo?is_edit=false'
    });
  },
  updatedrinking(that,data){
  	if(data){
		if(data.drinking.hasDrinking == 'yes'){
		  that.setData({
			  drinking:'饮酒'+data.drinking.years
		  })
		}else{
			that.setData({
			  		drinking:'不饮酒'
			})
		}
  	}else{
  	  that.setData({
  		drinking:'未设置'
  	  })
  	}
  	if(data){
	  if(data.smoking.hasSmoking == 'yes'){
		  that.setData({
			  smoking:'吸烟'+data.smoking.years
		  })
	  }else{
		  that.setData({
			smoking:'不吸烟'
		  })
	  }
  	}else{
  	  that.setData({
  		smoking:'未设置'
  	  })
  	}  
  },
	//健康史
  navigateToHealthHistory: function() {
	  const that = this
    wx.navigateTo({
      url: '/vp_pz/pages/familydoctor/healthhistory',
	  events: {
	    // 接收新增返回的数据
	    addHealthNote: (newHealth) => {
	  	  console.log(newHealth)
	      this.setData({
	        'healthData': newHealth
	      });
		  this.updatedrinking(this,newHealth.personal)
	    }
	  },
	  success: function(res) {
		// 通过 eventChannel 向被打开页面传送数据
		res.eventChannel.emit('addHealthNote', that.data.healthData)
	  }
    });
  },

  navigateToMedicalRecords: function() {
    wx.navigateTo({
      url: '/vp_pz/pages/familydoctor/medicalrecords?tab=outpatient'
    });
  },

  navigateToMedicationPlan: function() {
    wx.navigateTo({
      url: '/vp_pz/pages/familydoctor/medicationplan'
    });
  },

  // 上传记录
  uploadRecord: function(e) {
    const type = e.currentTarget.dataset.type;
	wx.navigateTo({
	    url: `/vp_pz/pages/familydoctor/medicalrecords?tab=${type}`
	  });
    // wx.chooseMessageFile({
    //   count: 1,
    //   type: 'file',
    //   success(res) {
    //     const tempFile = res.tempFiles[0];
    //     console.log('选择的文件:', tempFile);
    //     wx.showToast({
    //       title: `${type}上传成功`,
    //       icon: 'success'
    //     });
    //   }
    // });
  },
getFamilyData:function(){
	var that = this
	  app.util.request({
		  url: 'Familydoctor/getFamilyData',
		  data: {},
		  success(res) {
			  var data = res.data.data;
			  wx.setStorageSync('create_data',0)
			  if(data.length == 0){					  
				  wx.setStorageSync('can_edit_baseinfo',true)
				  wx.navigateTo({
					url: '/vp_pz/pages/familydoctor/baseinfo?is_edit=true&is_self=1'
				  });
			  }else{
				  console.log(data)
				  let activeUer = wx.getStorageSync('activeUser')
				  
				  const refresh_familydoctor = wx.getStorageSync('refresh_familydoctor')
				  if(!activeUer || refresh_familydoctor == 1){
					wx.setStorageSync('activeUser',data[0])
					activeUer = data[0]
				  }
				  wx.setStorageSync('refresh_familydoctor',0)
				  console.log('activeUer:',activeUer)
				  console.log(data.length)
				  that.setData({
					'users':data,
					'vipNum':data.length,
					'activeUser':activeUer
				  });
				  that.getHealthNoteData()
				  that.getMedicalInfo()
				  that.getMedicalPlanOnGoing()
			  }
		  }
	  })
},
//获取健康史
getHealthNoteData:function(){
	var that = this
	  app.util.request({
		  url: 'Familydoctor/getHealthNote',
		  data: {
			  'family_id':this.data.activeUser.id
		  },
		  success(res) {
			  var data = res.data.data;
			  console.log(data)
			  
			  that.updatedrinking(that,data.personal)
			  that.setData({
				  'healthData':data
			  })
		  }
	  })
},
//获取就医资料
getMedicalInfo:function(){
	var that = this
	  app.util.request({
		  url: 'Medicalmanage/getMedicalInfo',
		  data: {
			  'family_id':this.data.activeUser.id
		  },
		  success(res) {
			  var data = res.data.data;
			  console.log('MedicalInfo：',data)
			  let medicalRecordsData = [];
			  that.data.medicalRecords.forEach(function(element) {
			      if(data.includes(element.type)){
					  element.show = true;
				  }
				  medicalRecordsData.push(element)
			  });
			  that.setData({
				  'MedicalInfo':data,
				  'medicalRecords':medicalRecordsData
			  })
		  }
	  })
},
//获取用药计划
getMedicalPlanOnGoing:function(){
	var that = this
	  app.util.request({
		  url: 'Medicalmanage/getMedicalPlanOnGoing',
		  data: {
			  'family_id':this.data.activeUser.id
		  },
		  success(res) {
			  var data = res.data.data;
			  console.log('medicationPlans：',data)
			  
			  that.setData({
				  'medicationPlans':data
			  })
		  }
	  })
},
  onLoad: function(options) {
    // 页面加载时的逻辑
	let self = this;
	let aid = '';
	  if(!aid){
		  aid=wx.getStorageSync('VP_AID');
	  }
	  
	  app.util.getUserInfo(function (response) {
	  	console.log("==获取当前用户信息1==");
	  	console.log(response);
	  	self.setData({
	  		userInfo: response
	  	});
	  	console.log("==应用初始化：应用配置/应用中用户信息/当前城市信息==");
	  	
	  	setTimeout(function(){
	  		app.mdInit(function (cfg,mine,area) {
	  			self.setData({
	  				cfg: cfg,
	  				mine:mine,
	  				area:area,
	  				is_vip:mine.is_vip,
	  				quanyi:cfg.family_benefits,
					selectedContent:mine.content||[]
	  			});
				self.watchQuanyiContent()
	  			self.getFamilyData()
	  				let vip = wx.getStorageSync('VIP_STASTUS')
	  				if (!vip) {
	  					wx.redirectTo({ url: '/vp_pz/pages/familydoctor/membershipGuide' });
	  				}
	  		},{
	  				aid:self.data.aid,
	  				fuid:self.data.fuid,
	  				stid:self.data.fuid
	  		},true);
	  	},500)
	  });
	  
	
  },
  onShow:function(){
	  let is_create_data = wx.getStorageSync('create_data')
	  let vip = wx.getStorageSync('VIP_STASTUS')
	  if (!vip) {
	  	wx.redirectTo({ url: '/vp_pz/pages/familydoctor/membershipGuide' });
	  }else{
		  if(is_create_data == 1){
			  this.getFamilyData()
		  }
	  }
  },
  
  //监听器
  watchQuanyiContent(){
  	  let content = this.data.selectedContent
  	  let bentfitSelect = false;
  	  let benefitData = [];
  	  if(content.length > 0){
  		  this.data.quanyi.forEach((value, index, array) => {
  			  console.log('索引:', index, '值:', value);
  			  // array 是原数组的引用
  			  if(content.includes(index.toString())){
  				  bentfitSelect = true
  			  }else{
  				  bentfitSelect = false
  			  }
  			  benefitData.push({
  				  selected:bentfitSelect,
  				  content:value
  			  });
  			});
  	  }
  	  this.setData({
  		  processedList:benefitData
  	  })
  	  console.log("processedList:",this.data.processedList)
  },
  // 切换tab
    switchTab: function(e) {
      const tab = e.currentTarget.dataset.tab;
      this.setData({
        currentTab: tab
      });
    },
    
    
    // 添加用药计划
    addMedication: function() {
		let tempId=['afmN2h-kgkaR5WNP1G6FNuUX5JKryjI-vFzSbcSpGZg']; 
		wx.requestSubscribeMessage({
		  tmplIds: tempId,
		  success (res) {
		    if (res[tempId] === 'accept') {
		      console.log('用户同意了')  
		  
		    }else if(res[tempId] == 'reject') { // 用户拒绝授权
		      wx.showModal({
		        title: '温馨提示',
		        content: "您已关闭消息推送，如需要消息推送服务，请点击确定跳转设置页面打开授权后再次尝试。",
		        success: function(modal) {
		            if (modal.confirm) { // 点击确定
		                wx.openSetting({ withSubscriptions: true })
		            }
		        }
		    })
		    }
		   },
		   fail(err) { 
		     console.log(err)
		     if (err.errCode == '20004') {
		      wx.showModal({
		          title: '温馨提示',
		          content: "您的消息订阅主已关闭，如需复习提醒服务，请点击确定跳转设置页面打开授权后再次尝试。",
		          success: function(modal) {
		              if (modal.confirm) { // 点击确定
		                  wx.openSetting({ withSubscriptions: true })
		              }
		          }
		      })
		  }
		    },
		    complete(res) {
		      console.log('complete  调用完成')
		      // 无论取消还是接收都会执行:比如 下单(无论订阅号是取消还是接收都执行)
		      wx.navigateTo({
		        url: '/vp_pz/pages/familydoctor/editmedicationplan'
		      });
		    }
		})
      
    },
    
    // 编辑用药计划
    editMedication: function(e) {
      const planId = e.currentTarget.dataset.id;
	  wx.navigateTo({
		url: `/vp_pz/pages/familydoctor/editmedicationplan?id=${planId}`
	  });
    },
    
    // 删除用药计划
    deleteMedication: function(e) {
      const id = e.currentTarget.dataset.id;
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这个用药计划吗？',
        success: (res) => {
          if (res.confirm) {
            const plans = this.data.medicationPlans.filter(item => item.id !== id);
            this.setData({
              medicationPlans: plans
            });
			var that = this
			  app.util.request({
				  url: 'Medicalmanage/delMedicalPlan',
				  data: {
					  'id':id
				  },
				  success(res) {
					  wx.showToast({
					    title: '删除成功',
					    icon: 'success'
					  });
				  }
			  })
            
          }
        }
      });
    },
    
    // 设置用药提醒
    setReminder: function(e) {
      const id = e.currentTarget.dataset.id;
      const medication = this.data.medicationPlans.find(item => item.id === id);
      if (medication) {
        wx.showModal({
          title: '设置提醒',
          content: `设置${medication.name}的用药提醒`,
          success(res) {
            if (res.confirm) {
              // 实际开发中这里应该调用提醒设置API
              console.log('设置提醒:', medication);
            }
          }
        });
      }
    },
    
    // 编辑基本信息
    editBasicInfo: function() {
		wx.setStorageSync('can_edit_baseinfo',true)
      wx.navigateTo({
        url: '/vp_pz/pages/familydoctor/baseinfo?is_edit=true'
      });
    },
});